package com.szgr.baoyin.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.adapter.StoreListAdapter;
import com.szgr.baoyin.model.Goods;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.PopMenuDate;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 配件商城
 */
public class AccessoryStoreActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, AdapterView.OnItemClickListener, AbsListView.OnScrollListener {

    private RadioButton rb_first;
    private RadioButton rb_second;
    private RadioButton rb_third;
    private RadioButton rb_fourth;
    private List<Goods> showData;
    private StoreListAdapter listAdapter;
    private int currentPage = 1;
    private String currentId = "1140";
    private ListView accessoryListView;
    private RadioButton cb_sort;
    private RadioButton cb_saleNum;
    private String key = "";
    private String order = "";
    private PopupWindow popupWindow;
    private RadioGroup goodstypeRadioGroup;
    private RadioButton rb_filter;
    private int pos = 0;
    private String goodsName = "";
    private String minPrice = "";
    private String maxPrice = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_accessory_store);
        super.onCreate(savedInstanceState);
//        String s = "src=\"http://upload.lyg1.com/2015/1012/1444616461780.jpg\"";
//        s.replaceAll("\\\\(\"http:.*\\.jpg)\\\\\"","$1\"");
//        System.out.println("----regex------>" + s);
    }

    @Override
    public void initActionBar() {
        actionBarTitle.setText("配件商城");
        actionBarRight.setImageResource(R.drawable.car);
        actionBarRight.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(MyApplication.getmInstance().getCartNum() > 0){
            actionBarCount.setVisibility(View.VISIBLE);
            actionBarCount.setText(MyApplication.getmInstance().getCartNum() + "");
        }else{
            actionBarCount.setVisibility(View.GONE);
        }
    }

    @Override
    public void initView() {
        showData = new ArrayList<>();

        goodstypeRadioGroup = (RadioGroup) findViewById(R.id.accessory_radio_group);
        goodstypeRadioGroup.setOnCheckedChangeListener(this);
        rb_first = (RadioButton) findViewById(R.id.accessory_first);
        rb_second = (RadioButton) findViewById(R.id.accessory_second);
        rb_third = (RadioButton) findViewById(R.id.accessory_third);
        rb_fourth = (RadioButton) findViewById(R.id.accessory_fourth);

        accessoryListView = (ListView) findViewById(R.id.accessory_store_list_view);
        listAdapter = new StoreListAdapter(this, showData);
        accessoryListView.setAdapter(listAdapter);
        accessoryListView.setOnItemClickListener(this);
        accessoryListView.setOnScrollListener(this);
        rb_first.setChecked(true);

        LinearLayout ll_filter = (LinearLayout) findViewById(R.id.accessory_choose_type);
        ll_filter.setOnClickListener(this);

        cb_sort = (RadioButton) findViewById(R.id.tool_store_sort);
        cb_sort.setOnClickListener(this);
        cb_saleNum = (RadioButton) findViewById(R.id.tool_store_sale_num);
        cb_saleNum.setOnClickListener(this);
        rb_filter = (RadioButton) findViewById(R.id.tool_store_filter);
        rb_filter.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.action_bar_right:
                if(MyApplication.getmInstance().isLogin()) {
                    startActivity(new Intent(this, CartActivity.class));
                }else {
                    startActivity(new Intent(this,LoginActivity.class));
                }
                break;
            case R.id.accessory_choose_type:
                //TODO PopupWindow
                break;
            case R.id.tool_store_sort:
                cb_sort.setChecked(true);
                cb_saleNum.setChecked(false);
                cb_sort.setText("综合排序");
                key = "";
                order = "";
                showPopupWindow();
                currentPage = 1;
                showData.clear();
                getGoods(currentId, key, order);
                break;
            case R.id.tool_store_sale_num:
                cb_sort.setChecked(false);
                cb_sort.setText("综合排序");
                cb_sort.setSelected(false);
                cb_saleNum.setChecked(true);
                key = "1";
                order = "2";
                hidePopupWindow();
                currentPage = 1;
                showData.clear();
                getGoods(currentId, key, order);
                break;
            case R.id.out:
                hidePopupWindow();
                break;
            case R.id.filter_zonghe:
                key = "";
                order = "";
                cb_sort.setText("综合排序");
                cb_sort.setSelected(false);
                cb_sort.setChecked(true);
                hidePopupWindow();
                currentPage = 1;
                showData.clear();
                getGoods(currentId, key, order);
                break;
            case R.id.filter_price_low_to_high:
                key = "2";
                order = "1";
                cb_sort.setText("价格");
                cb_sort.setSelected(true);
                cb_sort.setChecked(false);
                hidePopupWindow();
                currentPage = 1;
                showData.clear();
                getGoods(currentId, key, order);
                break;
            case R.id.filter_price_high_to_low:
                key = "2";
                order = "2";
                cb_sort.setText("价格");
                cb_sort.setSelected(false);
                cb_sort.setChecked(true);
                hidePopupWindow();
                currentPage = 1;
                showData.clear();
                getGoods(currentId,key,order);
                break;
            case R.id.tool_store_filter:
                Intent intent = new Intent(this, FilterAccessoryActivity.class);
                intent.putExtra("position",pos);
                startActivityForResult(intent, 308);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(data != null){
            switch (resultCode){
                case 309:
                    currentPage = 1;
                    showData.clear();
                    pos = data.getIntExtra("position", 0);
                    goodsName = data.getStringExtra("filter");
                    minPrice = data.getStringExtra("low");
                    maxPrice = data.getStringExtra("high");
                    //设置大类的选中
                    RadioButton rb = (RadioButton) goodstypeRadioGroup.getChildAt(pos);
                    goodstypeRadioGroup.check(rb.getId());
                    //查询商品
                    getGoods(currentId,key,order);
                    break;
            }
        }
    }

    private void hidePopupWindow() {
        if(popupWindow != null && popupWindow.isShowing()){
            popupWindow.dismiss();
            popupWindow = null;
        }
    }

    private void showPopupWindow() {
        if(popupWindow != null && popupWindow.isShowing()){
            popupWindow.dismiss();
            popupWindow = null;
        }else {
            View view = LayoutInflater.from(this).inflate(R.layout.layout_store_filter, null);
            view.findViewById(R.id.out).setOnClickListener(this);
            view.findViewById(R.id.filter_zonghe).setOnClickListener(this);
            view.findViewById(R.id.filter_price_low_to_high).setOnClickListener(this);
            view.findViewById(R.id.filter_price_high_to_low).setOnClickListener(this);
            view.measure(0, 0);
            popupWindow = new PopupWindow(view, MyTool.getScreenWidth(getWindowManager()),MyTool.getScreenHeight(getWindowManager()));
            popupWindow.showAsDropDown(cb_sort);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId){
            case R.id.accessory_first:
                changeTextColor(rb_first, rb_second, rb_third, rb_fourth);
                currentPage = 1;
                showData.clear();
                listAdapter.setData(showData);
                currentId = "1140";
                goodsName = "";
                getGoods(currentId,key,order);
                pos = 0;
                break;
            case R.id.accessory_second:
                changeTextColor(rb_second,rb_first,rb_third,rb_fourth);
                currentPage = 1;
                showData.clear();
                listAdapter.setData(showData);
                currentId = "1421";
                goodsName = "";
                getGoods(currentId,key,order);
                pos = 1;
                break;
            case R.id.accessory_third:
                changeTextColor(rb_third,rb_second,rb_first,rb_fourth);
                currentPage = 1;
                showData.clear();
                listAdapter.setData(showData);
                currentId = "1152";
                getGoods(currentId,key,order);
                pos = 2;
                goodsName = "";
                break;
            case R.id.accessory_fourth:
                changeTextColor(rb_fourth,rb_second,rb_third,rb_first);
                currentPage = 1;
                showData.clear();
                listAdapter.setData(showData);
                currentId = "1386";
                goodsName = "";
                getGoods(currentId,key,order);
                pos = 3;
                break;
        }
    }

    private void changeTextColor(RadioButton rb1, RadioButton rb2, RadioButton rb3, RadioButton rb4) {
        rb1.setTextColor(0xffffffff);
        rb2.setTextColor(0xff234b64);
        rb3.setTextColor(0xff234b64);
        rb4.setTextColor(0xff234b64);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        if(MyApplication.getmInstance().isLogin()) {
            Intent storeIntent = new Intent(this,StoreDeatilActivity.class);
            storeIntent.putExtra("goods_id", listAdapter.getData().get(position).getGoods_id());
            storeIntent.putExtra("type",Constant.TYPE_03);
            startActivity(storeIntent);
//        }else{
//            ToastUtils.showToast("请登录后查看商品详情");
//        }
    }

    /**
     * 获取商品
     */
    private void getGoods(final String gc_id,final String key,final String order) {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_GET_GOODS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("----->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.getString("code");
                            if("200".equals(code) && jsonObject.has("datas")){
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                JSONArray goods_list = datas.getJSONArray("goods_list");
                                Gson gson = new Gson();
                                List<Goods> data = (List<Goods>)gson.fromJson(goods_list.toString(), new TypeToken<List<Goods>>() {
                                }.getType());
                                if(data.size() == 0){
                                    ToastUtils.showToast("没有更多商品了");
                                }
                                showData.addAll(data);
                                listAdapter.setData(showData);
                                currentPage ++ ;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
//                map.put("store_id","");
                map.put("goods_name",goodsName);
                map.put("gc_id",gc_id);
//                map.put("gc_deep","1");
                map.put("min_price",minPrice);
                map.put("max_price",maxPrice);
//                map.put("goods_state","1");
                map.put("key",key);
                map.put("order",order);
                map.put("page",currentPage + "");
                map.put("pagesize",Constant.PAGE_SIZE + "");
//                map.put("imgsize",Constant.IMG_SIZE + "");
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if(scrollState == SCROLL_STATE_IDLE){
            if(accessoryListView.getLastVisiblePosition() == accessoryListView.getCount() - 1) {
                getGoods(currentId,key,order);
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }
}
